/* $Id: ContestProblemsServlet.java 130 2011-08-26 06:58:30Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.servlets;


import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import alt.djudge.frontend.server.datatypes.AbstractEntry;
import alt.djudge.frontend.server.datatypes.ContestProblemEntry;
import alt.djudge.frontend.server.models.ContestProblemsModel;
import alt.djudge.frontend.server.models.CoreInterface;


public class ContestProblemsServlet extends AbstractDataServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	protected CoreInterface<? extends AbstractEntry> getModel()
	{
		return ContestProblemsModel.getCore();
	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void processAction(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		if ("dump".equals(action))
		{
			Document doc = dumpData();
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(resp.getOutputStream(), format);
			writer.write(doc);			
		}
		else if ("upload".equals(action))
		{
			try
			{
				Document doc = DocumentHelper.parseText(req.getParameter("xml"));
				Element el = doc.getRootElement();
				Iterator elementIterator = el.elementIterator();
				while (elementIterator.hasNext())
				{
					new ContestProblemEntry((Element)elementIterator.next()).makePersistent();
				}
			}
			catch (DocumentException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	public static Document dumpData()
	{
		Document doc = DocumentHelper.createDocument();
		Element el = doc.addElement("ContestProblems");
		
		List<ContestProblemEntry> list = ContestProblemsModel.getAllEntries();
		for (ContestProblemEntry problemEntry : list)
			el.add(problemEntry.getXml().getRootElement());
		
		return doc;
	}

	@Override
	protected boolean processEdit(HttpServletRequest req,
			HttpServletResponse resp)
	{
/*		String contestId = req.getParameter("contestId");
		String problemId = req.getParameter("problemId");
		String sid = req.getParameter("sid");
		String name = req.getParameter("name");
		String problemActive = (null != req.getParameter("active")) ? "true" : "false";
	//	id = ContestProblemsModel.editContestProblem(id, contestId, problemId, problemActive, sid, name); */
		return true;
	}
}
